'''
Desc: 带界面查询天气 - 输入城市编码，不同城市对应的编码可查询doc/weather_district_id.csv文件
Author: 陈爱国
Date: 2024-09-01 17:40:42
'''
from PyQt5.QtWidgets import QWidget, QApplication, QGridLayout, QLineEdit, QTextEdit, QPushButton
import sys
import requests
import json

class Weather(QWidget):
    def __init__(self):
        super(Weather, self).__init__()

        self.setWindowTitle("查询天气")

        # 栅格布局
        layout = QGridLayout()

        # 城市输入框
        self.input_city = input_city = QLineEdit()
        input_city.setPlaceholderText = "请输入城市"
        layout.addWidget(input_city, 0, 0)
        
        # 查询按钮
        search_btn = QPushButton("查询")
        layout.addWidget(search_btn, 0, 1)
        search_btn.clicked.connect(self.searchweather)

        # 结果文本框
        self.search_result = search_result = QTextEdit()
        layout.addWidget(search_result, 1, 0, 1, 2)

        # 设置窗口为栅格布局
        self.setLayout(layout)

    def searchweather(self):
        # 获得输入的城市编码
        citycode = self.input_city.text()

        header = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36'
        }

        url = 'https://api.map.baidu.com/weather/v1/?district_id={}&data_type=all&ak=uz0Bo4eMgdGnkCyFtfkfws0FibuC1m4H'.format(citycode)
        result = requests.get(url, headers=header)
        self.search_result.setText(result.text)


if __name__ == '__main__':
    app = QApplication(sys.argv)

    win = Weather()
    win.show()

    sys.exit(app.exec_())


